package com.ww.core.util.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;

import com.ww.core.util.Logger;
import com.ww.core.util.StringUtils;


/**
 * @since 
 * @version 2013-12-5
 * @author wangwei
 */
public class HttpClientUtil {
	private static DefaultHttpClient httpclient = null;
	private static final int REQUEST_TIMEOUT = 30 * 1000;//设置请求超时10秒钟  
	private static final int SO_TIMEOUT = 60 * 1000; //设置等待数据超时时间10秒钟 

	/**
	 * 异步请求.   
	 * @param a  Activity
	 * @param url 链接
	 * @param id 返回id
	 * @param map post请求参数
	 */
	public static void getJsonByAsyn(Context context, Activity a, String url, int id, HashMap<String, String> map) {
		if (map == null) {
			RequestObject obj = new RequestObject(a, url, new HashMap<String, String>());
			new HttpTask().start(obj, id, HttpTask.REQUEST_TYPE_GET);
		} else {
			RequestObject obj = new RequestObject(a, url, map);
			new HttpTask().start(obj, id, HttpTask.REQUEST_TYPE_POST);
		}
	}

	/**
	 * get请求获取json数据.
	 * @param url    请求链接
	 * @return JSONObject
	 */
	public static JSONObject getJsonByGet(Context context, String url) {
		httpclient = MyHttpClient.getHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);//连接时间
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);//数据传输时间
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpclient.execute(httpget);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
		return getJSONObject(response);
	}

	/**
	 * post请求获取json数据.
	 * @param url  请求链接
	 * @param map   参数
	 * @return JSONObject
	 */
	public static JSONObject getJsonByPost(Context context, String url, Map<String, String> map) {
		Logger.info(url);
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair nvp = null;
		if (map != null) {
			Set<Map.Entry<String, String>> entryseSet = map.entrySet();
			for (Map.Entry<String, String> entry : entryseSet) {
				nvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
				params.add(nvp);
			}
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(params), HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {
			throw new IllegalArgumentException("Unable to encode http parameters.");
		}
		httpclient = MyHttpClient.getHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);//连接时间
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);//数据传输时间
		HttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
		return getJSONObject(response);
	}

	/**
	 * json转换.
	 * @param response HttpResponse
	 * @return JSONObject
	 */
	private static JSONObject getJSONObject(HttpResponse response) {
		try {
			StringBuilder builder = new StringBuilder();
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));
				for (String s = reader.readLine(); s != null; s = reader.readLine()) {
					builder.append(s);
				}
				JSONObject jsonObject = null;
				if ((builder.toString().contains("<html>")) || ("".equals(builder.toString()))) {
					return null;
				} else {
					jsonObject = new JSONObject(builder.toString());
				}
				Logger.info("getJSONObject========================");
				Logger.info(jsonObject.toString());
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 转化post请求参数.
	 * @param nameValuePairs List<NameValuePair>
	 * @return List<NameValuePair>
	 */
	private static List<NameValuePair> stripNulls(List<NameValuePair> nameValuePairs) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (null != nameValuePairs) {
			for (NameValuePair nameValuePair : nameValuePairs) {
				if (StringUtils.isNotEmpty(nameValuePair.getValue())) {
					params.add(nameValuePair);
				}
			}
		}
		return params;
	}

}
